import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class DetailController extends GetxController
    implements CeramicInteractionObserver, CeramicDeleteObserver {
  DetailController();

  // 仓库
  final CommentRepository _commentRepository = CommentRepository(
    Get.find<DatabaseService>(),
  );
  final CeramicInteractionRepository _interactionRepository =
      CeramicInteractionRepository();
  final CeramicRepository _ceramicRepository = CeramicRepository();
  final UserFollowRepository _userFollowRepository = UserFollowRepository();
  final UserRepository _userRepository = UserRepository();
  final BrowseRecordRepository _browseRecordRepository =
      BrowseRecordRepository();

  // 评论文本控制器
  late TextEditingController commentController;

  // 评论列表
  final RxList<CommentModel> comments = <CommentModel>[].obs;
  final RxBool isLoadingComments = false.obs;

  // 陶瓷数据
  final Rx<Ceramic?> ceramicData = Rx<Ceramic?>(null);

  // 创作者用户信息
  final Rx<User?> creatorUser = Rx<User?>(null);

  // 评论用户列表
  final RxList<User> commentUsers = <User>[].obs;
  final RxBool isLoadingUsers = false.obs;

  // 浏览用户列表
  final RxList<User> viewedUsers = <User>[].obs;
  final RxBool isLoadingViewedUsers = false.obs;

  // 陶瓷ID
  String? ceramicId;
  int? ceramicIdInt;
  int? creatorUserId;

  // 点赞、收藏、关注状态
  final RxBool isLiked = false.obs;
  final RxBool isFavorited = false.obs;
  final RxBool isFollowed = false.obs;

  // 获取评论列表
  Future<void> loadComments() async {
    if (ceramicId == null) return;

    isLoadingComments.value = true;
    try {
      final contentComments = await _commentRepository.getCommentsForContent(
        ceramicId!,
        CommentType.ceramic,
      );

      comments.value = contentComments;

      // 更新评论用户列表
      _updateCommentUsers();
    } catch (e) {
      print('获取评论失败: $e');
    } finally {
      isLoadingComments.value = false;
    }
  }

  // 更新评论用户列表
  void _updateCommentUsers() {
    isLoadingUsers.value = true;
    try {
      // 获取所有评论用户的ID和头像
      final Map<String, User> uniqueUsers = {};

      for (var comment in comments) {
        if (!uniqueUsers.containsKey(comment.userId)) {
          uniqueUsers[comment.userId] = User(
            id: int.tryParse(comment.userId),
            username: comment.userName,
            avatar: comment.userAvatar,
            createdAt: DateTime.now(),
            updatedAt: DateTime.now(),
          );
        }
      }

      commentUsers.value = uniqueUsers.values.toList();
    } catch (e) {
      print('获取评论用户失败: $e');
    } finally {
      isLoadingUsers.value = false;
    }
  }

  // 加载浏览用户列表
  Future<void> loadViewedUsers() async {
    if (ceramicIdInt == null) return;

    isLoadingViewedUsers.value = true;
    try {
      final users = await _browseRecordRepository.getViewedUsersByContent(
        ceramicIdInt!,
        BrowseType.ceramic,
        limit: 5,
      );
      viewedUsers.value = users;
    } catch (e) {
      print('获取浏览用户失败: $e');
    } finally {
      isLoadingViewedUsers.value = false;
    }
  }

  // 记录浏览记录
  Future<void> recordBrowseHistory(int userId) async {
    if (ceramicIdInt == null) return;

    try {
      final record = BrowseRecord(
        userId: userId,
        contentId: ceramicIdInt!,
        type: BrowseType.ceramic,
        browseTime: DateTime.now(),
      );

      await _browseRecordRepository.addBrowseRecord(record);
      print('记录浏览历史成功: userId=$userId, ceramicId=$ceramicIdInt');

      // 刷新浏览用户列表
      loadViewedUsers();
    } catch (e) {
      print('记录浏览历史失败: $e');
    }
  }

  // 添加评论
  Future<void> addComment() async {
    if (ceramicId == null || commentController.text.trim().isEmpty) return;

    final UserService userService = Get.find<UserService>();

    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to comment',
      onLoggedIn: () async {
        final currentUser = userService.currentUser.value!;
        final commentText = commentController.text.trim();

        try {
          final newComment = CommentModel(
            id: '', // 由仓库生成UUID
            content: commentText,
            userId: currentUser.id.toString(),
            userName: currentUser.nickname ?? currentUser.username,
            userAvatar: currentUser.avatar ?? '',
            contentId: ceramicId!,
            type: CommentType.ceramic,
            createdAt: DateTime.now(),
          );

          await _commentRepository.addComment(newComment);
          commentController.clear(); // 清空输入框
          await loadComments(); // 重新加载评论
        } catch (e) {
          print('添加评论失败: $e');
        }
      },
    );
  }

  // 检查交互状态
  Future<void> checkInteractionStatus(int userId) async {
    if (ceramicIdInt == null) return;

    // 检查是否已点赞
    isLiked.value = await _interactionRepository.hasLiked(
      userId,
      ceramicIdInt!,
    );

    // 检查是否已收藏
    isFavorited.value = await _interactionRepository.hasFavorited(
      userId,
      ceramicIdInt!,
    );

    // 获取陶瓷数据
    try {
      final ceramic = await _ceramicRepository.getCeramicById(ceramicIdInt!);
      if (ceramic != null) {
        ceramicData.value = ceramic;
        creatorUserId = ceramic.userId;
      }
    } catch (e) {
      print('获取陶瓷数据失败: $e');
    }

    // 加载创作者信息
    if (creatorUserId != null) {
      // 检查是否已关注创作者
      isFollowed.value = await _userFollowRepository.isFollowing(
        userId,
        creatorUserId!,
      );

      // 获取创作者信息
      try {
        final creator = await _userRepository.getUserById(creatorUserId!);
        if (creator != null) {
          creatorUser.value = creator;
        }
      } catch (e) {
        print('获取创作者信息失败: $e');
      }
    }
  }

  // 点赞操作
  Future<bool> toggleLike(int userId) async {
    if (ceramicIdInt == null) return false;

    if (isLiked.value) {
      // 取消点赞
      final result = await _interactionRepository.unlikeCeramic(
        userId,
        ceramicIdInt!,
      );
      if (result) {
        isLiked.value = false;
        update(["detail"]);
      }
      return result;
    } else {
      // 点赞
      final result = await _interactionRepository.likeCeramic(
        userId,
        ceramicIdInt!,
      );
      if (result) {
        isLiked.value = true;
        update(["detail"]);
      }
      return result;
    }
  }

  // 收藏操作
  Future<bool> toggleFavorite(int userId) async {
    if (ceramicIdInt == null) return false;

    if (isFavorited.value) {
      // 取消收藏
      final result = await _interactionRepository.unfavoriteCeramic(
        userId,
        ceramicIdInt!,
      );
      if (result) {
        isFavorited.value = false;
        update(["detail"]);
      }
      return result;
    } else {
      // 收藏
      final result = await _interactionRepository.favoriteCeramic(
        userId,
        ceramicIdInt!,
      );
      if (result) {
        isFavorited.value = true;
        update(["detail"]);
      }
      return result;
    }
  }

  // 关注操作
  Future<bool> toggleFollow(int followerId) async {
    if (creatorUserId == null) {
      print('创作者ID为空，无法执行关注操作');
      return false;
    }

    print(
      '执行关注操作: followerId=$followerId, followingId=$creatorUserId, 当前关注状态=${isFollowed.value}',
    );

    try {
      if (isFollowed.value) {
        // 取消关注
        print('正在执行取消关注...');
        final result = await _userFollowRepository.unfollowUser(
          followerId: followerId,
          followingId: creatorUserId!,
        );
        print('取消关注结果: $result');
        if (result) {
          isFollowed.value = false;
          update(["detail"]);
        }
        return result;
      } else {
        // 关注
        print('正在执行关注...');
        final follow = await _userFollowRepository.followUser(
          followerId: followerId,
          followingId: creatorUserId!,
        );
        print('关注结果: ${follow != null}');
        if (follow != null) {
          isFollowed.value = true;
          update(["detail"]);
          return true;
        }
        return false;
      }
    } catch (e) {
      print('关注操作异常: $e');
      return false;
    }
  }

  // 举报陶瓷作品
  void reportCeramic() {
    if (ceramicData.value == null || ceramicIdInt == null) return;

    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报陶瓷作品: $ceramicIdInt, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 删除陶瓷作品
        try {
          // 使用Repository删除陶瓷作品，这将通知所有观察者
          final success = await _ceramicRepository.deleteCeramic(ceramicIdInt!);

          if (success) {
            // 显示成功提示
            EasyLoading.showSuccess('你将不会再看到此内容');

            // 返回上一页
            Future.delayed(Duration(seconds: 1), () {
              Get.back();
            });
          } else {
            EasyLoading.showError('举报失败，请稍后再试');
          }
        } catch (e) {
          print('删除陶瓷作品失败: $e');
          EasyLoading.showError('举报失败，请稍后再试');
        }

        return true;
      },
    );
  }

  // 举报评论
  void reportComment(CommentModel comment) {
    ReportBottomSheet.show(
      onReport: (reason) async {
        // 这里可以实现实际的举报逻辑，如发送到服务器
        print('举报评论: ${comment.id}, 原因: ${reason.toString()}');

        // 模拟API调用
        await Future.delayed(Duration(seconds: 1));

        // 删除评论
        try {
          await _commentRepository.deleteComment(comment.id);

          // 显示成功提示
          EasyLoading.showSuccess('评论已被删除');

          // 重新加载评论
          await loadComments();
        } catch (e) {
          print('删除评论失败: $e');
          EasyLoading.showError('举报失败，请稍后再试');
        }

        return true;
      },
    );
  }

  _initData() async {
    // 从路由参数中获取陶瓷对象
    if (Get.arguments != null && Get.arguments is Map) {
      final ceramic = Get.arguments['ceramic'] as Ceramic?;

      // 检查交互状态
      final UserService userService = Get.find<UserService>();

      // 如果直接传递了ceramic对象，直接使用它
      if (ceramic != null) {
        ceramicData.value = ceramic;

        // 从ceramic对象获取ID
        ceramicId = ceramic.id?.toString();
        ceramicIdInt = ceramic.id;
        creatorUserId = ceramic.userId;

        // 加载浏览用户列表
        if (ceramicIdInt != null) {
          loadViewedUsers();
        }

        // 加载创作者信息
        if (creatorUserId != null) {
          try {
            final creator = await _userRepository.getUserById(creatorUserId!);
            if (creator != null) {
              creatorUser.value = creator;
            }
          } catch (e) {
            print('获取创作者信息失败: $e');
          }
        }

        // 加载评论
        if (ceramicId != null) {
          await loadComments();
        }

        // 如果用户已登录，检查交互状态并记录浏览历史
        if (userService.isLoggedIn.value &&
            userService.currentUser.value?.id != null &&
            ceramicIdInt != null) {
          int userId = userService.currentUser.value!.id!;
          await checkInteractionStatus(userId);

          // 记录浏览历史
          await recordBrowseHistory(userId);
        }
      }
      // 如果没有传递ceramic对象，显示错误
      else {
        print('错误: 未传递ceramic对象');
      }
    }
    update(["detail"]);
  }

  void onTap() {}

  @override
  void onInit() {
    super.onInit();
    commentController = TextEditingController();
    // 注册为观察者，接收陶瓷交互状态更新
    CeramicInteractionRepository.addObserver(this);
    // 注册为观察者，接收陶瓷删除通知
    CeramicRepository.addObserver(this);
    // 立即初始化数据，不等到onReady
    _initData();
  }

  @override
  void onReady() {
    super.onReady();
    // 确保UI已完全准备好后再次检查状态
    final UserService userService = Get.find<UserService>();
    if (userService.isLoggedIn.value &&
        userService.currentUser.value?.id != null &&
        ceramicIdInt != null) {
      checkInteractionStatus(userService.currentUser.value!.id!);
    }
  }

  @override
  void onClose() {
    // 取消注册观察者
    CeramicInteractionRepository.removeObserver(this);
    CeramicRepository.removeObserver(this);
    commentController.dispose();
    super.onClose();
  }

  // 实现CeramicInteractionObserver接口
  @override
  void onLikeStatusChanged(int userId, int ceramicId, bool isLiked) {
    final UserService userService = Get.find<UserService>();
    if (userService.currentUser.value?.id == userId &&
        ceramicIdInt == ceramicId) {
      this.isLiked.value = isLiked;

      // 更新作品数据中的点赞数
      if (ceramicData.value != null && ceramicData.value!.id == ceramicId) {
        ceramicData.value = ceramicData.value!.copyWith(
          likeCount:
              isLiked
                  ? ceramicData.value!.likeCount + 1
                  : ceramicData.value!.likeCount - 1,
        );
      }
      update(["detail"]);
    }
  }

  @override
  void onFavoriteStatusChanged(int userId, int ceramicId, bool isFavorited) {
    final UserService userService = Get.find<UserService>();
    if (userService.currentUser.value?.id == userId &&
        ceramicIdInt == ceramicId) {
      this.isFavorited.value = isFavorited;

      // 更新作品数据中的收藏数
      if (ceramicData.value != null && ceramicData.value!.id == ceramicId) {
        ceramicData.value = ceramicData.value!.copyWith(
          favoriteCount:
              isFavorited
                  ? ceramicData.value!.favoriteCount + 1
                  : ceramicData.value!.favoriteCount - 1,
        );
      }
      update(["detail"]);
    }
  }

  // 实现CeramicDeleteObserver接口
  @override
  void onCeramicDeleted(int ceramicId) {
    if (ceramicIdInt == ceramicId) {
      // 如果当前正在查看的陶瓷作品被删除，返回上一页
      Get.back();
    }
  }
}
